/** 
 * @copyright		all rights reserved.
 * @author			how_fly@yahoo.com
 * @brief			download the page from internet using curl-library
 *
 * @version			1.0
 * @date
 * 
 * 
 */
#ifndef _DOWNLOAD_MANAGER_H_
#define _DOWNLOAD_MANAGER_H_


#include "url.h"

#include <curl/curl.h>
#include <list>
#include <pthread.h>
using namespace std;

///the number of threads to download web-page 
#define DOWNLOAD_THREADS_COUNT  10

struct page_t;

/**
 * @brief using in the curl-lib, the pblock will store the raw content 
 * 		  of web-page
 * 
 * 
 * 
 */
struct memory_block
{
	unsigned char* pblock;
	size_t len;
};

/**
 * @brief 1.depend on the urls, to download web-page
 * 
 * 
 * 
 */
struct download_manager_t
{
	///'true' will jump out of the cycle, clear the memory, and quit,
	bool quit;	
	
	///the threads for downloading web-pages,
	///and the pthread_mutex and the pthread_cond
	list<url_t*> urls[DOWNLOAD_THREADS_COUNT];
	pthread_mutex_t lockers[DOWNLOAD_THREADS_COUNT];
	pthread_cond_t conds[DOWNLOAD_THREADS_COUNT];
};

/**
 *  @brief 	start the multi-threads. each thread will download web-page
 * 			in its own cycle.
 *  @param [in]download_manager_t 
 *  @return int: 0 is good, -1 is error.
 */ 
int init_download_manager(download_manager_t& g_download_manager);

/**
 *  @brief 	add one url to one thread, which will download web-page
 * 			in its own cycle.
 *  @param [in]url_t 
 *  @param [in]download_manager_t 
 *  @return int: 0 is good, -1 is error.
 */
int add_url_to_download_manager(url_t* url, download_manager_t* download_manager);

/**
 *  @brief 	add one team of urls to these threads,one url to one thread, which will download web-page
 * 			in its own cycle.
 *  @param [in]list<url_t*>
 *  @param [in]download_manager_t 
 *  @return int: 0 is good, -1 is error.
 */
int add_urls_to_download_manager(list<url_t*>& urls, download_manager_t* download_manager);

/**
 *  @brief 	download_manager_t will jump out of the cycle in each thread
 *  @param [in]download_manager_t 
 *  @return void
 */
void quit_download_manager(download_manager_t* download_manager);



extern download_manager_t g_download_manager;

#endif
